using System;
using System.Collections.Generic;
using UnityEngine;
namespace Spine {
    [Serializable]
    public class SkinSet {
        [SerializeField]
        public List<SkinSetData> skinSetList;
        [NonSerialized]
        SkeletonData data;
        [NonSerialized]
        Skin defaultSkin;
        [NonSerialized]
        Dictionary<string, HashSet<string>> skinName_partNameDic;

        public void Init(SkeletonData data) {
            this.data = data;
            defaultSkin = data.defaultSkin;
            data.skinSet = this;
            skinName_partNameDic = new Dictionary<string, HashSet<string>>();
            if (skinSetList != null && skinSetList.Count > 0) {
                foreach (var setData in skinSetList) {
                    foreach (var skinName in setData.skinArr) {
                        if (skinName_partNameDic.TryGetValue(skinName, out var partSet) == false) {
                            partSet = new HashSet<string>();
                            skinName_partNameDic[skinName] = partSet;
                        }
                        partSet.Add(setData.name);
                    }
                }
            }
            if (data.defaultSkin.name == "default") {
                data.defaultSkin = AddSkin(defaultSkin, data);
            }
        }

        public Skin AddSkin(Skin skin, SkeletonData data) {
            Skin cdSkin = new Skin($"{skin.name}_set");
            cdSkin.AddSkin(skin);
            if (skin.name != "default") {
                cdSkin.AddSkin(defaultSkin);
            }
            if (skinName_partNameDic == null) {
                Init(data);
            }
            if (skinName_partNameDic.TryGetValue(skin.name, out var partSet)) {
                foreach (var part in partSet) {
                    var newSkin = data.FindSkin(part);
                    cdSkin.AddSkin(newSkin);
                }
            }
            return cdSkin;
        }
    }
    [Serializable]
    public class SkinSetData {
        public string name;
        public string[] skinArr;
    }
}
